package com.example.NettyStudy;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017/5/25.
 */
public class MySimpleServerHandle extends ChannelHandlerAdapter {
    private ByteBuf sendBuf;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        byte[] req = "hello world".getBytes();
        sendBuf = Unpooled.copiedBuffer(req);
        ctx.writeAndFlush(sendBuf);
        System.out.println("服务端发送信息成功! ");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf readByf = (ByteBuf) msg;
        byte[] req = new byte[readByf.readableBytes()];
        readByf.readBytes(req);
        String reqString = new String(req);
        System.out.println("服务端获取信息成功! [" + reqString + "]");
        //加密信息
        String respString = encryptByMD5(reqString);
        ByteBuf respByf = Unpooled.copiedBuffer(respString.getBytes());
        ctx.writeAndFlush(respByf);
        System.out.println("服务端响应数据成功! ["+respString+"]");
    }

    private String encryptByMD5(String reqString) {
        String result = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64 = new BASE64Encoder();
            byte[] digest = md5.digest(reqString.getBytes());
            result = base64.encode(digest);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }


}
